﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FinanSoft.Entities;
using FinanSoft.BusinessLayer;
using FinanSoft.Utilities;
using System.Collections;

namespace FinanSoft.PresentacionInventario
{
    public partial class frmIOMercancia : Form
    {
        private int[] _storeIds;
        private int[] _itemIds;
        private List<int> _accountIds;
        private List<int> _auxAccountIds;
        private int[] _currencyIds;

        int tipoOp; // 1 - Entrada, 2 - Salida

        public frmIOMercancia(int _tipoOp)
        {
            tipoOp = _tipoOp;

            InitializeComponent();
            
            //Llena los combos
            llenarBodegas();
            llenarCuenta();
            llenarAticulos();
            fillCurrencies();

            // Cambia los valores del form segun operacion
            if (tipoOp == 1) //Entrada
            {
                this.Text = "Entrada de mercancias";

                lblCosto.Visible = true;
                txtCosto.Visible = true;
                cmbCurrency.Visible = true;
                labelMoneda.Visible = true;
            }
            else //salida
            {
                this.Text = "Salida de mercancias";

                lblCosto.Visible = false;
                txtCosto.Visible = false;
                cmbCurrency.Visible = false;
                labelMoneda.Visible = false;
            }
        }

        /// <summary>
        /// Agrega al combo box de monedas todas las monedas
        /// </summary>
        private void fillCurrencies()
        {
            int selectedId = Constants.INVALID_ID;
            List<Currency> addedCurrencies = MoneyManager.GetInstance().GetAddedCurrencies();
            _currencyIds = new int[addedCurrencies.Count + 2];
            for (int currencyIndex = 0; currencyIndex < addedCurrencies.Count; currencyIndex++)
            {
                _currencyIds[currencyIndex] = addedCurrencies[currencyIndex].Id;
                cmbCurrency.Items.Add(addedCurrencies[currencyIndex].Name);
            }
            Currency sys = MoneyManager.GetInstance().SystemCurrency;
            _currencyIds[_currencyIds.Length - 2] = sys.Id;
            cmbCurrency.Items.Add(sys.Name);
            Currency local = MoneyManager.GetInstance().LocalCurrency;
            _currencyIds[_currencyIds.Length - 1] = local.Id;
            cmbCurrency.Items.Add(local.Name);
            if (selectedId != Constants.INVALID_ID)
                cmbCurrency.SelectedIndex = selectedId;
            else
                cmbCurrency.SelectedIndex = cmbCurrency.Items.Count - 1;
        }

        /// <summary>
        /// Llena el combobox con las bodegas a consultar
        /// </summary>
        private void llenarBodegas()
        {
            cmbBodegas.Items.Clear();

            List<StoreRoom> stores = StoreRoomManager.GetInstance().GetStoreRooms();
            if (!StoreRoomManager.GetInstance().IsError)
            {
                _storeIds = new int[stores.Count];

                for (int ele = 0; ele < stores.Count; ele++)
                {
                    _storeIds[ele] = stores[ele].Id;
                    cmbBodegas.Items.Add(stores[ele].Name);
                }
            }
            else
            {
                MessageBox.Show(StoreRoomManager.GetInstance().ErrorMessage, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
            }

            cmbBodegas.SelectedIndex = 0;
        }

        /// <summary>
        /// Llena el combobox con las bodegas a consultar
        /// </summary>
        private void llenarAticulos()
        {
            cmbArticulo.Items.Clear();

            List<Item> items = ItemManager.GetInstance().GetItems();
            if (!ItemManager.GetInstance().IsError)
            {
                _itemIds = new int[items.Count];

                for (int ele = 0; ele < items.Count; ele++)
                {
                    _itemIds[ele] = items[ele].Id;
                    cmbArticulo.Items.Add(items[ele].Descripción);
                }
            }
            else
            {
                MessageBox.Show(StoreRoomManager.GetInstance().ErrorMessage, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
            }

            cmbArticulo.SelectedIndex = 0;
        }

        /// <summary>
        /// Llena los combos de cuentas con los valores de las cuentas contables
        /// </summary>
        private void llenarCuenta()
        {
            AccountingCatalog catalog;

            cmbCuenta.Items.Clear();
            
            _accountIds = new List<int>();
            _auxAccountIds = new List<int>();
            catalog = CatalogManager.GetInstance().GetAccountingCatalog();
            foreach (Account account in catalog.PrincipalAccounts)
                addAccount(account);
            foreach (AuxiliarAccount auxAcc in AuxiliaryAccountManager.GetInstance().GetAuxiliarAccountsList().Values)
            {
                _auxAccountIds.Add(auxAcc.AccountID);
                cmbCuenta.Items.Add(auxAcc.DisplayName);        
            }
            cmbCuenta.SelectedIndex = 0;            
        }

        /// <summary>
        /// Agrega una cuenta no titulo al combo
        /// </summary>
        /// <param name="account"></param>
        private void addAccount(Account account)
        {
            if (!account.IsTitle)
            {
                _accountIds.Add(account.AccountID);
                cmbCuenta.Items.Add(account.DisplayName);                
            }
            else
                foreach (Account child in account.Children.Values)
                    addAccount(child);
        }

        private void btnSalir_Click(object sender, EventArgs e)
        {
            Close();
        }

        private bool validateInformation()
        {
            return (cmbArticulo.SelectedIndex != Constants.INVALID_ID && cmbBodegas.SelectedIndex != Constants.INVALID_ID &&
               cmbCuenta.SelectedIndex != Constants.INVALID_ID && txtCantidad.Text.Trim().Length > 0 &&
               (tipoOp == 2 || (cmbCurrency.SelectedIndex != Constants.INVALID_ID && txtCosto.Text.Trim().Length > 0)));
        }

        private void btnActInfo_Click(object sender, EventArgs e)
        {
            //Extrae el id de la bodega seleccionada
            if(validateInformation())
            {
                int accountId;
                int auxAccId;
                if(cmbCuenta.SelectedIndex >= _accountIds.Count)
                {
                    AuxiliarAccount auxAcc = AuxiliaryAccountManager.GetInstance().GetAuxiliarAccount(_auxAccountIds[cmbCuenta.SelectedIndex - _accountIds.Count]);
                    accountId = auxAcc.Parent;
                    auxAccId = auxAcc.AccountID;
                }
                else
                {
                    accountId = _accountIds[cmbCuenta.SelectedIndex];
                    auxAccId = Constants.INVALID_ID;
                }
                bool result;
                if (tipoOp == 1)
                {
                    double localUnitCost = Convert.ToDouble(txtCosto.Text) * MoneyManager.GetInstance().GetCurrency(_currencyIds[cmbCurrency.SelectedIndex]).ToLocalCurrency;
                    result = ItemManager.GetInstance().MakeInventoryInputMovement(
                        _itemIds[cmbArticulo.SelectedIndex], _storeIds[cmbBodegas.SelectedIndex], localUnitCost,
                        Convert.ToInt32(txtCantidad.Text), accountId, auxAccId, Constants.IE_ACCOUNTING_ENTRY);
                }
                else
                    result = ItemManager.GetInstance().MakeInventoryOutputMovement(
                        _itemIds[cmbArticulo.SelectedIndex], _storeIds[cmbBodegas.SelectedIndex],
                        Convert.ToInt32(txtCantidad.Text), accountId, auxAccId, Constants.II_ACCOUNTING_ENTRY);
                if(result)
                    MessageBox.Show(MessageConstants.INVENTORY_OP_SUCCESS, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                else
                    MessageBox.Show(ItemManager.GetInstance().ErrorMessage, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
                MessageBox.Show(MessageConstants.MISSING_FIELDS, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void txtCantidad_KeyPress(object sender, KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }

        private void txtCosto_KeyPress(object sender, KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }
    }
}
